<template>
  <div class="view">
    <el-row class="handle-box">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAdd"
        >{{$t("export.addTemplate")}}</el-button
      >
    </el-row>
    <div class="tablebox">
    <template>
      <el-table :data="tables" size="mini" stripe class="tablefisbox">
        <el-table-column type="index" :label="$t('public.number')" width="150">
        </el-table-column>
        <el-table-column prop="modelName" :label="$t('export.templateName')">
        </el-table-column>
        <el-table-column prop="modelType" :label="$t('export.templateType')">
        </el-table-column>
        <el-table-column :label="$t('public.operation')">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleExport(scope.$index, scope.row)"
              >{{ $t("export.export") }}</el-button
            >
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >{{ $t("public.edit") }}</el-button
            >
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="handleDel(scope.$index, scope.row)"
              >{{ $t("public.del") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </template>

    <el-col class="pages">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="pageSize"
        :total="total"
      >
      </el-pagination>
    </el-col>

    <!-- 编辑界面 -->
    <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        width="700px"
      >
      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item :label="$t('export.templateName')" prop="filename">
          <el-input v-model="editForm.filename" :disabled="dbAccount"></el-input>
        </el-form-item>
        <el-form-item :label="$t('export.templateType')">
          <el-select v-model="editForm.modeltype"  @change="showwitsname(editForm.modeltype)" :disabled="dbAccount" clearable :placeholder="$t('public.text')">
            <el-option
              v-for="item in templateTypes"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-form-item :label="$t('export.tableName')">
            <el-select v-model="tableName" @change="showcanshu(tableName)" clearable :placeholder="$t('public.text')">
              <el-option
                v-for="(item,index) in tableNames"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <span  class="dialogTit">{{tableNameTit}}</span>
        </el-row>
        <el-form-item :label="$t('export.dataField')">
          <ul class="infinite-list" style="overflow:auto">
            <li v-for="(i,idx) in dataField" class="infinite-list-item" :class="active == idx ? 'isActive' : ''" @click="addField(i,idx)">{{ i }}</li>
          </ul>
        </el-form-item>
        <el-table
          :data="editForm.dataparams"
          size="mini" 
          max-height="160px"
          border
          :cell-style = "{fontSize:'14px',padding:'0'}"
          :header-cell-style = "{fontSize:'14px'}"
          style="width: 100%">
          <el-table-column prop="tableName" :label="$t('export.tableName')"></el-table-column>
          <el-table-column prop="itemNo" :label="$t('export.itemNo')"></el-table-column>
          <el-table-column prop="witsMnemonic" :label="$t('export.witsMnemonic')"></el-table-column>
          <el-table-column prop="ifsMnemonic" width='200' :label="$t('export.ifsMnemonic')"></el-table-column>
          <el-table-column prop="unit" :label="$t('curvecon.unit')"></el-table-column>
          <el-table-column :label="$t('public.operation')">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="deleteRow(scope.$index, editForm.dataparams)"
                type="text"
                size="small">
                {{ $t("public.del") }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button @click.native="dialogFormVisible = false" type="primary">{{
            $t("public.cancelbtn")
          }}</el-button>
          <el-button
            v-if="dialogStatus == 'create'"
            type="primary"
            @click="createData"
            >{{ $t("public.savebtn") }}</el-button
          >
          <el-button v-else type="primary" @click="updateData">{{
            $t("public.changebtn")
          }}</el-button>
        </div>
    </el-dialog>

    <!-- 导出界面 -->
    <el-dialog
        :title="$t('export.export')"
        :visible.sync="dialogExportVisible"
        :close-on-click-modal="false"
        width="500px"
      >
      <el-form :model="exportForm" :rules="editExportRules" ref="editExportRules">
        <el-form-item :label="$t('export.templateType') +'：'">
          <span v-text="exportForm.modeltype"></span>
        </el-form-item>
        <el-form-item :label="$t('export.timezone')" v-if="exportForm.modeltype == '时间模板'">
          <el-select v-model="timezone" filterable @change="showdata">
            <el-option
              v-for="(item,index) in timezones"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('export.wellname')">
          <el-select v-model="wellname" filterable @change="showdata">
            <el-option
              v-for="(item,index) in wellnames"
              :key="index"
              :label="item.wellName"
              :value="item.wellName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('export.availableData')">
          <span v-text="availableData"></span>
        </el-form-item>
        <template v-if="exportForm.modeltype == '深度模板'">
          <el-form-item :label="$t('export.start')" prop="start">
            <el-input v-model="exportForm.start"></el-input>
          </el-form-item>
          <el-form-item :label="$t('export.end')" prop="end">
            <el-input v-model="exportForm.end"></el-input>
          </el-form-item>
          <el-form-item :label="$t('export.interval')" prop="interval">
            <el-input v-model="exportForm.interval"></el-input>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item :label="$t('export.statrTime')" prop="statrTime">
            <el-date-picker
              v-model="exportForm.start"
              type="datetime"
              :placeholder="$t('public.opDate')"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              default-time="08:00:00"
              >
            </el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('export.endTime')" prop="endTime">
            <el-date-picker
              v-model="exportForm.end"
              type="datetime"
              :placeholder="$t('public.opDate')"
              value-format="yyyy-MM-dd HH:mm:ss"
              align="right"
              :picker-options="pickerOptions"
              default-time="20:00:00"
              >
            </el-date-picker>
          </el-form-item>
        </template>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportType('LAS1')">{{$t("export.export1")}}</el-button>
        <el-button type="primary" @click="exportType('LAS2')">{{$t("export.export2")}}</el-button>
        <el-button type="primary" @click="exportType('EXCEL')">{{$t("export.exportExcel")}}</el-button>
        <el-button @click.native="dialogExportVisible = false" type="primary">{{
          $t("public.cancelbtn")
        }}</el-button>
      </div>
    </el-dialog>

    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogStatus: "", //编辑框界面切换
      textMap: {
        //添加与编辑界面
        update: this.$t("public.edit"),
        create: this.$t("public.create"),
      },
      dialogFormVisible: false, //弹窗
      dialogExportVisible: false, //导出
      tables: [], //表格数据
      total: 0, //总共条数
      page: 1, //请求页
      limit: 10, //页条数
      pageSize: 1, //当前页
      dbAccount: false,
      active: 0, //默认选中字段
      //是否必填项
      editFormRules: {
        filename: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
      },
      editExportRules: {
        start: [{ required: true, message: "请输入开始参数", trigger: "blur" }],
        end: [{ required: true, message: "请输入结束参数", trigger: "blur" }],
        interval: [{ required: true, message: "请输入间隔", trigger: "blur" }]
      },  
      //编辑界面数据
      editForm: {
        filename: "",
        modeltype: "",
        dataparams: [],
      },
      exportForm: {
        filename:"", //文件名称
        modeltype: "", //模板类型
        start: "",//开始深度
        end: "",//结束深度
        interval:"",//间隔
        lang:"", //语言
      },
      tableName: "",
      tableNames: [],//表名
      tableNameTit:"",//表明提示文字
      dataField: [],//数据字段
      timezones:[],//时区列表
      wellnames:[],//井名列表
      availableData: "", //可用数据
      timezone:"",//时区
      wellname: "",//井名

      //模板类型
      templateTypes: [
        {
          value: '1',
          label: "时间模板",
        },
        {
          value: '2',
          label: "深度模板",
        },
      ],
      pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
    };
  },
  mounted() {
    this.getmodel();
  },

  methods: {
    handleSizeChange(val) {
      this.limit = val;
      this.getmodel();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.pageSize = val;
      this.getmodel();
    },
    //导出参数
    handleExport(index,row){
      this.dialogExportVisible = true;
      // if(row.modelType == '深度模板'){
      //   // this.exportForm
      // }else{
      //   this.getshiqu();
      // }
      this.exportForm = {
        filename:row.modelName,
        modeltype:row.modelType,
        // availableData:""
      }
      this.getSelect(row.modelType);
    },
    //编辑参数
    handleEdit(index, row) {
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.dbAccount = true;
      this.active = 0;
      this.editForm = {
        filename: row.modelName,
        modeltype: row.modelType,
        createUser: JSON.parse(this.$store.state.userInfo).uid,
        // tableName: row.tableName,
        // tableNames: row.tableNames,
        // tableNameTit: row.tableNameTit,
        // dataField: row.dataField,
        // dataparams: res.data,
      };
      this.showwitsname(row.modelType)
      this.getxml(row.modelName);
      
    },
    //新增参数
    handleAdd() {
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.dbAccount = false;
      this.active = 0;
      this.editForm = {
        filename: "",
        modeltype: "",
        createUser: JSON.parse(this.$store.state.userInfo).uid,
        // tableNames: [],//表名
        // tableNameTit:"",//表明提示文字
        // dataField: [],
        dataparams: [],
      };
      this.tableName =  "",
      this.tableNames =  [];//表名
      this.tableNameTit = "";//表明提示文字
      this.dataField= [];
      // this.dataparams= []
    },
    //获取模板文件
    async getmodel() {
      try {
        let res = await this.$api.management.getmodel();
        this.total = res.count;
        this.tables = res.data;
      } catch (e) {
        console.log(e);
      }
    },
    //根据模板类型获取 wits表名
    async showwitsname(modeltype) {
      try {
        let params = {
          modeltype: modeltype,
        };
        let res = await this.$api.management.showwitsname(params);
        this.tableNames = res.data;
        this.tableName = res.data[0];
        this.showcanshu(this.tableName)
      } catch (e) {
        console.log(e);
      }
    },
    //根据表名显示参数字段及表描述
    async showcanshu(tableName) {
      try {
        let params = {
          witsname: tableName,
        };
        let res = await this.$api.management.showcanshu(params);
        this.dataField = res.data;
        this.tableNameTit = res.data2;
      } catch (e) {
        console.log(e);
      }
    },
    // 根据模板名称加载模板文件
    async getxml(filename) {
      try {
        let params = {
          filename: filename,
        };
        let res = await this.$api.management.getxml(params);
        this.editForm.dataparams = res.data;
      } catch (e) {
        console.log(e);
      }
    },
    //获取时区下拉列表(区分中英文) 井名
    async getSelect(modeltype) {
      try {
        if(modeltype == "时间模板"){
          let params = {
            lang: this.$store.state.language,
          };
          let shiQu = await this.$api.management.getshiqu(params);
          this.timezones = shiQu.data;
          this.timezone = "东8区北京台北";
        }
        let wellName = await this.$api.set.getwellname();
        this.wellnames = wellName.data;
        this.wellname = wellName.data[0].wellName;
        this.showdata()
      } catch (e) {
        console.log(e);
      }
    },
    //显示可用数据
    async showdata() {
      try {
        let params = {
          filename: this.exportForm.filename,
          wellname: this.wellname,
          lang: this.$store.state.language,
          timearea: this.timezone,
        };
        let res = await this.$api.management.showdata(params);
        this.availableData = res.data;
      } catch (e) {
        console.log(e);
      }
    },
    //导出las 1.0、las 2.0、excel(深度、时间)
    async exportType(type) {
      try {
        let params = {
          lang: this.$store.state.language,
          filename: this.exportForm.filename,
          modeltype: this.exportForm.modeltype,
          wellname: this.wellname,
          start: this.exportForm.start,
          end: this.exportForm.end,
          interval: this.exportForm.interval,
          timearea: this.timezone,
          exporttype: type,
        };
        let res = await this.$api.management.exportfile(params);
        var blob = new Blob([res], { type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8' });
        var downloadElement = document.createElement('a');
        var href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = params.filename+'.xls';
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
      } catch (e) {
        console.log(e);
      }
    },
    //添加
    createData() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          let params = Object.assign({}, this.editForm);
          params.dataparams =  this.editForm.dataparams.map(item => item.tableName + ',' + item.itemNo + ',' + item.witsMnemonic + ',' + item.ifsMnemonic + ',' + item.unit);
          let res = await this.$api.management.savexml(params);
          if (res.code == 200) {
            this.$message({
              showClose: true,
              message: this.$t("public.addsuccess"),
              type: "success",
            });
            this.$refs["editForm"].resetFields(); //清空表单
            this.dialogFormVisible = false; //关闭弹窗
            this.getmodel(); //刷新数据
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        }
      });
    },
    //修改
    updateData() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          let params = Object.assign({}, this.editForm);
          params.dataparams =  this.editForm.dataparams.map(item => item.tableName + ',' + item.itemNo + ',' + item.witsMnemonic + ',' + item.ifsMnemonic + ',' + item.unit);
          let res = await this.$api.management.putxml(params);
          if (res.code == 200) {
            this.$message({
              showClose: true,
              message: this.$t("public.editsuccess"),
              type: "success",
            });
            this.$refs["editForm"].resetFields(); //清空表单
            this.dialogFormVisible = false;
            this.getmodel(); //刷新数据
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        }
      });
    },
    //删除
    handleDel(index, row) {
      // 二次确认删除
      this.$confirm(
        this.$t("public.confirmcontent"),
        this.$t("public.confirmtitle"),
        {
          type: "warning",
        }
      )
        .then(async () => {
          // this.tables.splice(index, 1);
          let params = {
            filename: row.modelName,
            usid: JSON.parse(this.$store.state.userInfo).uid,
          };
          let res = await this.$api.management.delexml(params);
          if (res.code == 200) {
            this.$message.success(this.$t("public.confirmtips1"));
            this.getmodel(); //刷新数据
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        })
        .catch(() => {});
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    addField(data,idx){
      this.active = idx;
      let obj = {};
      obj.tableName = data[0].split('.')[0];
      let data2 = data[1].split('[').join('').split(']');
      obj.itemNo = data2[0];
      obj.witsMnemonic = data2[1];
      obj.ifsMnemonic = data2[2]
      obj.unit = data2[3];
      this.editForm.dataparams.push(obj);
    },
  },
};
</script>

<style lang='less' scoped>
.infinite-list{
  width: 460px;
  height: 160px;
  border: 1px solid #3a5196;
  //页面右侧滑块
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-track {
    border-radius: 0;
    background: rgba(255, 249, 244, 0.1);
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 100px;
    background: #3a5196;
  }
  .infinite-list-item{
    padding-left: 5px;
    cursor: pointer;
  }
  .isActive{
    background: #3E86FB;
  }
}
.dialogTit{
  margin: 10px;
}
*{
  box-sizing:border-box;
}
input,select{
  width: 200px;
}
#words{
  display: none;
}
</style>